package com.hduong.springcloud.service.impl;

import com.hduong.springcloud.dao.OrderDao;
import com.hduong.springcloud.domain.Order;
import com.hduong.springcloud.service.AccountService;
import com.hduong.springcloud.service.OrderService;
import com.hduong.springcloud.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <h3>spring-cloud-demo-parent</h3>
 * <p>OrderServiceImpl </p>
 *
 * @author : hduong
 * @version : 1.0
 * @date : 2020-03-23 09:13
 **/
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private StorageService storageService;

    @Autowired
    private AccountService accountService;


    /**
     * 创建订单->调用库存服务扣减库存->调用账户服务扣减账户余额->修改订单状态
     */
    @Override
    //添加一个全局事务 --> 分布式事务注解 不加事务的话， 会出现数据不一致的问题
    @GlobalTransactional(name = "fsp-create-order", rollbackFor = Exception.class)
    public void create(Order order) {
        log.info("-------------->下单开始");
        //本应用创建订单
        orderDao.create(order);

        //远程调用库存服务扣减库存
        log.info("-------------->order-service中扣减库存开始");
        storageService.decrease(order.getProductId(), order.getCount());
        log.info("-------------->order-service中扣减库存结束");

        //远程调用账户服务减少余额
        log.info("-------------->order-service中扣减余额开始");
        accountService.decrease(order.getUserId(), order.getMoney());
        log.info("-------------->order-service中扣减余额结束");

        //更新订单状态 为已完成 0表示已完成
        log.info("-------------->order-service中修改订单状态开始");
        orderDao.update(order.getUserId(), 1);
        log.info("-------------->order-service中修改订单状态结束");
    }
}
